#!/bin/bash

NET="192.168.0.1 \
192.168.1.1 \
192.168.2.1 \
192.168.3.1 \
192.168.4.1 \
192.168.5.1 \
192.168.6.1 \
192.168.7.1" 

ONCNT=0

function PINGDEST() 
{
	ping -c 1 -W 2 $1 &>/dev/null
	return $?
}

function PINGGATE() 
{
	for i in `seq 1 255`
	do 
	{
		dest=$1.$i
		PINGDEST $dest 
		if [ $? -eq 0 ]; then
			echo $dest >> $cnt_file 
		fi
	}&
	done
}

function INFO() 
{
	win=`tput cols`
	iplen=${#1} #iplen=`echo $1|wc -L`

	if [ $win -gt "30" ]; then
		space=$((30-$iplen))
	else
		space=$(($win-$iplen))
	fi

	echo -n "$1"
	for i in `seq 1 $space`
	do
		echo -en " "
	done
	echo -e "\033[32m[up]\033[0m"
}

function PINGSUM()
{
	for net in $NET
	do
		gate=${net%.*}
		
		echo "ping $gate.x ..."
		PINGGATE $gate 
		wait #wait for child processes
	done

	for i in `cat $cnt_file`
	do
		INFO $i
		((ONCNT++))
	done

	echo -e "\033[32m$ONCNT hosts online\033[0m"
}

function EXIT() 
{
	echo -e "\033[31m \n\nexiting....\033[0m" && exit 7
}

#start 
#capture ctrl+c signal, kill -l can list all signals
trap 'EXIT' INT 

cnt_file="/tmp/$$.cnt"
touch $cnt_file

PINGSUM

rm $cnt_file 

exit 0

#echo -en "\033[33mplease your GATEWAY:\033[0m"
#read N


